<?php

namespace app\api\controller\haipi;

use app\admin\model\UserMoneyLog;
use app\api\service\OrderService;
use app\api\service\VpayService;
use app\common\controller\Frontend;
use app\common\model\haipi\Order as OrderModel;
use think\facade\Db;
use think\facade\Cache;
class Order extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['index'];
    
    // 支付类型常量
    const PAY_TYPE_BALANCE = 1; // 余额支付类型



    
    /**
     * 通用VIP订单创建方法
     * 
     * @param string $payType 支付类型
     * @param bool $useBalance 是否使用余额
     * @return OrderModel|null
     */
    protected function createVipOrderCommon($payType, $useBalance = false): array
    {
        // 使用验证器验证参数
        $validate = new \app\api\validate\VipValidate();
        $data = $this->request->post();
        if (!$validate->scene('upVip')->check($data)) {
            $this->error($validate->getError());
        }

        $vipId = $data['vip_id'];
        $userinfo = $this->auth->getUser();
        
        // 检查VIP是否存在
        $vipLevel = $validate->checkVipExists($vipId);
        
        // 检查用户余额是否足够
        $useBalance && $validate->checkUserBalance($userinfo, $vipLevel);
        
        // 检查用户是否已经是永久会员
        $validate->checkUserVipStatus($userinfo);
        // 检查VIP是否重复购买
        $validate->checkVipIsRepeat($userinfo, $vipLevel);
  
        $orderData = [];

        Db::transaction(function() use($vipLevel, $userinfo, $payType, $useBalance,  &$orderData) {
            $orderService = app(OrderService::class);
            $vpayService = app(VpayService::class);

            //关闭相同的订单
            $this->closeAlikeOrder($userinfo->id, OrderModel::GOODS_TYPE_VIP, $vipLevel->id);
           
            // 生成唯一交易号
            $traceNo = $orderService->generateUniqueNo();

            $amount = $vipLevel->sale_price;
            if (!$useBalance) {
                // 创建vpay订单
                $result = $vpayService->createOrder($traceNo, $vipLevel->sale_price, $payType);
                $amount = $result['amount'];
            }
         
            //创建本地订单
            $order = $orderService->createOrder($userinfo->id, $amount, OrderModel::GOODS_TYPE_VIP, $vipLevel->id, $payType, $traceNo);

            if ($useBalance) {
                 //余额处理
                $this->handleUserBalance($userinfo->id, $vipLevel->sale_price);
                //处理 VIP 信息
                $orderService->handleVip($userinfo, $vipLevel);
                // 佣金
                $orderService->handleCommission($userinfo, $order);
            }
            $orderData =  [
                'order_id' => $order->id,
                'amount' => $amount,
                'pay_type' => $payType,
                'trace_no' => $traceNo,
                'order_no' => $order->order_no,
                'payment_qrcode' => $result['qrcode'] ?? null,
                'expire_time' => $result['expire_time'] ?? null,
           ];
        });
        
       return $orderData; // 返回订单信息数组
    }
    
    protected function closeAlikeOrder($userId, $type, $goodsId){
        $alikeOrder = OrderModel::where('user_id', $userId,)
        ->where('status', OrderModel::ORDER_STATUS_NOPAY)
        ->where('goods_type', $type)
        ->where('goods_id', $goodsId)
        ->find();
        if(empty($alikeOrder)){
            return;
        }
        $vpayService = app(VpayService::class);
        $vpayService->closeOrder($alikeOrder->trade_no);
    }



    protected function handleUserBalance($userId, $amount)
    {
        UserMoneyLog::create([
            'memo' => '升级会员',
            'money' => -$amount,
            'user_id' => $userId
        ]);
    }
 
    public function createVipOrderByBalance()
    {
        $payType = self::PAY_TYPE_BALANCE;
        $this->createVipOrderCommon($payType, true);
        $this->success('升级成功');
    }


    public function createVipOrder()
    {
        $payType = $this->request->post('pay_type');
        if(empty($payType)){
            $this->error('参数不正确');
        }
        $data = $this->createVipOrderCommon($payType, false);
   
        $this->success('下单成功', $data);
    }

    public function cancel(){
        $orderId = $this->request->post('order_id');
        OrderModel::where('id', $orderId)
        ->where('status', "<>",OrderModel::ORDER_STATUS_PAIED)
        ->delete();
        $this->success("取消成功");
    }

    public function fundPaid(){
        $orderId = $this->request->post("order_id");   
        $order = OrderModel::where("id", $orderId)->field("status")->find();

        if(empty($order)){
            $this->error("订单不存在");
        }
        $this->success("", ['is_pay' => $order->status == OrderModel::ORDER_STATUS_PAIED ? 1 : 0]);
    }

}